package com.jadows.tdog.filter;

import com.jadows.tdog.constants.GlobalConstants;
import com.jadows.tdog.dto.UserInfo;
import com.jadows.tdog.properties.ChatServerProperties;
import com.jadows.tdog.util.SecurityUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Nonnull;
import java.io.IOException;

/**
 * token过滤器 验证token有效性
 */
@Component
@RequiredArgsConstructor
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    final ChatServerProperties properties;

    @Override
    protected void doFilterInternal(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull FilterChain filterChain) throws IOException, ServletException {
        if (isExcludePatterns(request, response, filterChain)) {
            return;
        }
        String memberId = request.getHeader(GlobalConstants.X_MEMBER_ID);
        try {
            UserInfo me = new UserInfo().setMemberId(memberId);
            SecurityUtil.setCurrentUser(me);
            filterChain.doFilter(request, response);
        } finally {
            SecurityUtil.removeCurrentUser();
        }
    }

    /**
     * 是否是不需要验证的路径
     */
    private boolean isExcludePatterns(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        String[] ignoreUrls = {".html", ".js", ".css"};
        String uri = request.getRequestURI();
        for (String ignoreUrl : ignoreUrls) {
            if (uri.endsWith(ignoreUrl)) {
                filterChain.doFilter(request, response);
                return true;
            }
        }
        return false;
    }
}
